<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\UserService;
use App\Exceptions\ValidationException;
use App\Http\Controllers\BaseController;

class WeChatController extends BaseController
{
    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }
    public function miniProgramLogin()
    {
        $param = $this->validationParameter([
            'code|code' => 'require',
        ]);

        $wechat = app('wechat.mini_program');

        $response = $wechat->auth->session($param['code']);
        $openid = data_get($response, 'openid');
        if (empty($openid)) {
            throw new ValidationException('缺失openid');
        }
        // $openid = "ooFXA67X-_mAG6QDltrEbij0l0Os";
        $result = $this->userService->login($openid);

        return $this->response->success($result);
    }

    public function update(Request $request)
    {
        $param = $this->validationParameter([
            'nickname|昵称' => 'require',
            'sex|性别' => 'noRequire',
            'avatar|头像' => 'require',
        ]);

        $param['uid'] = $request->user('api')->user_id ?? null;
        if (empty($param['uid'])) {
            throw new ValidationException('未获取到uid,请重新登录');
        }

        $result = $this->userService->update($param);

        return $this->response->success($result);
    }

    public function logout()
    {
        $result = auth('api')->logout();

        return $this->response->success($result);

    }

}
